﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using CDV.MC.MatrixDriver.WebApp.Service;

namespace CDV.MC.MatrixDriver.WebApp
{
    public static class ServiceLocator
    {
        public static IServiceProvider Instance { get; set; }
    }

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //.AddSessionStateTempDataProvider();//注册为SessionStateTempDataProvider，默认为CookieStateTempDataProvider

            //添加内存分布式缓存
            services.AddDistributedMemoryCache();

            //添加Session服务
            services.AddSession((config) => { config.IdleTimeout = TimeSpan.FromMinutes(20); });

            //添加WebSocketManager单例
            //services.AddSingleton<IWebSocketManagerService>(CreateWebSocketManagerService());
            //services.AddSingleton<IWebSocketManagerService, WebSocketManager>((sp)=>new WebSocketManager() { ServerPath = "ws://172.16.3.135:4649/matrix" });

            //添加HttpClient
            //services.AddTransient<IHttpClientProvider, HttpClientProvider>();
            services.AddTransient<IHttpClientProvider, HttpClientProvider>((serviceProvider)=> {
                return new HttpClientProvider()
                {
                    BaseUri = Configuration.GetValue<string>("Api:Matrix:BaseUrl")
                };
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var log4netConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config");
            var repository = log4net.LogManager.CreateRepository("MatrixDriver");
            log4net.Config.XmlConfigurator.ConfigureAndWatch(repository, new FileInfo(log4netConfigPath));

            //共享服务给Startup类以外的地方使用
            ServiceLocator.Instance = app.ApplicationServices;

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSession();

            app.UseWebSockets();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Matrix}/{action=Index}/{clientIP?}");
            });
        }

        //public WebSocketManager CreateWebSocketManagerService()
        //{
        //    var websocketManager = new WebSocketManager()
        //    {
        //        ServerPath = "ws://localhost:4649/matrix"
        //    };
        //    return websocketManager;
        //}
    }
}
